package com.safe.first.infrastructure.interceptor;

import cn.hutool.core.util.IdUtil;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mickey
 * @since 2022/6/17
 **/
public class TraceLogProcessFilter extends OncePerRequestFilter {

    public static final String TRACE_ID = "TRACE_ID";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        try {
            String tid = IdUtil.nanoId(10);
            MDC.put(TRACE_ID, tid);
            filterChain.doFilter(request, response);
        }
        finally {
            MDC.remove(TRACE_ID);
        }

    }
}
